(function ($) {
    $(document).on('mouseenter mouseleave', 'div.photo', function (e) {
        var $details = $(this).find('.details');
        if (e.type === 'mouseenter') {
            $details.fadeTo('fast', .7);
        } else {
            $details.fadeOut('fast');
        }
    });

    $('div.photo').on('mouseenter mouseleave', function (e) {
        $(this).find('.details').toggleClass('entered', e.type === 'mouseenter');
    });

    $(document).ready(function () {
        $('#more-photos').click(function (e) {
            e.preventDefault();
            $(this).trigger('nextPage', [true]);
        });
    });

    $(document).on('nextPage', function (e, scrollToVisible) {
        var url = $('#more-photos').attr('href');
        if (url) {
            $.get(url, function (data) {
                var $data = $(data).appendTo('#gallery');
                if (scrollToVisible) {
                    var newTop = $data.offset().top;
                    $(window).scrollTop(newTop);
                }
                checkScrollPosition();
            });
        }
    });

    var pageNum = 1;
    $(document).on('nextPage', function () {
        pageNum++;
        if (pageNum < 20) {
            $('#more-photos').attr('href', 'pages/' + pageNum + '.html');
        } else {
            $('#more-photos').remove();
        }
    });

    function checkScrollPosition() {
        var distance = $(window).scrollTop() + $(window).height();
        if ($('#container').height() <= distance) {
            $(document).trigger('nextPage');
        }
    }

    $.event.special.throttledScroll = {
        setup: function (data) {
            var timer = 0;
            $(this).on('scroll.throttledScroll', function (e) {
                if (!timer) {
                    timer = setTimeout(function () {
                        $(this).triggerHandler('throttledScroll');
                        timer = 0;
                    }, 250);
                }
            });
        },
        teardown: function () {
            $(this).off('scroll.throttledScroll');
        }
    }

    $(window).on('throttledScroll', checkScrollPosition).trigger('throttledScroll');
})(jQuery);